#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
#
# This file is part of Coruja-scripts
#
# Coruja-scripts is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Coruja-scripts is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Coruja-scripts.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2011 Grupo Falabrasil - http://www.laps.ufpa.br/falabrasil
#
# Author 2011: Pedro Batista - pedosb@gmail.com

import argparse
import sys
import re
from os.path import basename
from os.path import join
from scipy.io import wavfile

min_time = 20

def read_mlf(fn, output_dir=None):
	
	if output_dir == '' or output_dir is None:
		output_dir = '.'
	f = open(fn)
	
	if f.readline().strip() != '#!MLF!#':
		sys.stderr.write("Not a MLF file.\n")
		return None

	l = '.'
	ti = None
	prefix = None
	label = None
	stop = 0
	start = 0
	label_list = []
	factor = 10**-7
	out_f = None
	out_str = ''
	interval = 1 
	
	while True:
		write = True
		if l.strip() == '.':
			l = f.readline()
			if prefix is not None:
				interval -= 1
				
				# This is the begin of the TextGrid 
				out_f.seek(0,0)
				out_f.write('File type = "ooTextFile"\nObject class = "TextGrid"\nxmin = 0\nxmax = %f\ntiers? <exists>\n' % stop)
	                        out_f.write('size = 1\n' + 'item []:\n' + '\titem[1]:\n' + '\t\tclass = "IntervalTier"\n')
        	                out_f.write('\t\tname = "%s"\n' % prefix)
                	        out_f.write('\t\txmin = 0\n\t\txmax = %f\n' % stop)
				out_f.write('\t\tintervals: size = %d\n' % interval)

				# Puting the string out_str after the head of the TextGrid
				# This string will be set in the code below
				out_f.write(out_str)
				out_str = ''
			
			if out_f is not None:
				out_f.close()
			if l == '':
				break
				
				
			prefix = re.sub(r'^"(.*)\.rec"\n$', r'\1', l)
			out_f = open(join(output_dir, prefix) + '.TextGrid', 'w')
			interval = 1	
			write = False

		if write:
			# Take the first three columns of the .mlf file, because they are the informations we need
			start, stop, label, score = l.split()
			start = int(start) * factor
			stop = int(stop) * factor
			
			# Intervals of each word with their start and stop times
			# Saving these informations in a string out_str
			out_str += ('\t\tintervals [%d]\n' % interval)
			out_str += ('\t\t\txmin = %f\n' % start)
			out_str += ('\t\t\txmax = %f\n' % stop)
			out_str += ('\t\t\ttext = "%s"\n' % label)
			interval += 1

		l = f.readline()
		if l == '':
			break;

if __name__=='__main__':
	parser = argparse.ArgumentParser(description='')
	parser.add_argument('-m', '--mlf-file', required=True,
			help='Aligned MLF file')
	parser.add_argument('-o', '--output-dir',
			help='dir to store output TextGrid files')
	args = parser.parse_args()
	read_mlf(args.mlf_file, args.output_dir)
